﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;
using MyCode.IOC;
using Microsoft.AspNetCore.Http;

namespace MyCode.Tools
{
    public class CacheHelper : ICacheHelper, ITransientDependency
    {
        public IMemoryCache _memoryCache { get; set; }
        private static MemoryCacheEntryOptions options;
        public CacheHelper()
        {
            if (options == null)
            {
                options = new MemoryCacheEntryOptions();
            }

        }
        public T GetCache<T>()
        {
            string key = string.Empty;
            HttpContextHelper.GetInstance().HttpContext.Request.Cookies.TryGetValue("sessionID", out key);
            if (string.IsNullOrEmpty(key))
            {
                return default(T);
            }
            var obj = _memoryCache.Get<T>(key);
            return obj;
        }
        public void SetCache<T>(T t)
        {
            options.SlidingExpiration = TimeSpan.FromMinutes(30);//相对定时
            var key = string.Empty;
            HttpContextHelper.GetInstance().HttpContext.Request.Cookies.TryGetValue("sessionID", out key);
            if (!string.IsNullOrEmpty(key))
            {
                _memoryCache.Set<T>(key, t, options);
            }

        }

        public void SetCacheAbsolute<T>(T t)
        {
            throw new NotImplementedException();
        }

        public void Remove()
        {
            throw new NotImplementedException();
        }
    }
}
